package com.elite.groovy.callback

import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import com.elite.groovy.kh.KHUtil
import net.sf.json.JSONArray
import net.sf.json.JSONNull
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: apiLastPolicyNTSResultDto*
 * @Description:调用出单系统获取上年保单信息 *
 * @remak ：调用出单系统获取上年保单信息*
 * @author: TH*
 * @date 2024-03-22 11:11:00
 *
 */
public class apiLastPolicyNTSResultDto implements ServiceBackInvoke {

    private static final Log log = LogFactory.getLog(apiLastPolicyNTSResultDto.class);

    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        long starttime = System.currentTimeMillis();
        JSONObject backjson = new JSONObject();


        //获取接口调用方式及参数
        String GetMethod = httpServletRequest.getMethod();
        log.debug("[GetMethod]:" + GetMethod);

        String inData = "";
        if (GetMethod.equals("GET")) {
            inData = httpServletRequest.getParameter("data");
            log.debug("[原始Get请求参数：]" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(httpServletRequest.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("[原始Post请求参数：]" + inData);
        }


        if (KHUtil.isNull(inData)) {
            log.error("请求接口入参为空-无法完成操作！");
            backjson.put("code", '-1');
            backjson.put("msg", "请求接口入参为空-无法完成操作！")
            return backjson;
        }


        log.debug("apiLastPolicyNTSResultDto-version:20240411")
        try {

            JSONObject jsonObject = JSONObject.fromObject(inData);

            String customer_guid = GetJV(jsonObject, "customer_guid");//客户id
            String PolicyNos = GetJV(jsonObject, "policyNos"); //保单号
            String CustList_id = GetJV(jsonObject, "CustList_id");//批次号
            String obj_guid=GetJV(jsonObject,"obj_guid");


            List chaxunsqlList = eliteBean.chaxun_sql("select WEBSERVICEURL From sysc_interface where WEBTYPE='CD_URL' ", "dataSource");


            if (chaxunsqlList.size() > 0) {

                String url = chaxunsqlList.get(0).get("WEBSERVICEURL");


                log.debug("请求出单系统请求URL"+url.toString());
                JSONObject requstjson = new JSONObject();

                requstjson.put("policyNos", PolicyNos);

                log.debug("请求出单系统请求报文：" + requstjson.toString());

                //设置请求表头
                Map<String, String> TokenParams = new HashMap<String, String>();
                TokenParams.put("Content-Type", "application/json");
                long rquststarttime = System.currentTimeMillis();
              String rponsebody = Util.doHttpPostUseHead(url.toString(), requstjson.toString(), "UTF-8", 20000, 0, TokenParams);
                long rqustendtime = System.currentTimeMillis();

                log.debug("请求出单系统接口耗时：" + +(rqustendtime-rquststarttime)+"毫秒");
                log.debug("请求出单系统返回报文：" + rponsebody.toString());
                JSONObject rponsejson = JSONObject.fromObject(rponsebody);

                String  succ = GetJV(rponsejson, "succ");
                String errmsg = GetJV(rponsejson, "errMsg");
                if (succ.equals("true")) {

                    String delsql1 = '''delete from PREVIOUSYEARPOLICYINFO where objective_guid=?''';
                    String delsql2 = '''delete from PREVIOUSYEARPOLICYINFO_XB where objective_guid=?''';
                    String delsql3 = '''delete from PREVIOUSYEARPOLICYINFO_FC where objective_guid=?''';
                    jt.update(delsql1, obj_guid);
                    jt.update(delsql2, obj_guid);
                    jt.update(delsql3, obj_guid);

                    if (!JSONNull.getInstance().equals(rponsejson.get("data"))) {

                    JSONArray batcharr = rponsejson.getJSONArray("data");
                    log.debug("请求出单系统返回报文data：" + batcharr);

                    for (int i = 0; i < batcharr.size(); i++) {
                        JSONObject dataJson = batcharr.getJSONObject(i);

                        String host_orderNo = GetJV(dataJson, "orderNo");       //订单号
                        String host_policyNo = GetJV(dataJson, "policyNo");           //保单号
                        String host_startDate = GetJV(dataJson, "startDate");          //起保日期
                        String host_endDate = GetJV(dataJson, "endDate");            //终保日期
                        String host_companyCode = GetJV(dataJson, "companyCode");        //承保机构
                        String host_companyName = GetJV(dataJson, "companyName");     //承保机构名称
                        String host_ChannelDetailCode = GetJV(dataJson,"channelDetailCode");      //承保渠道
                        String host_riskCode = GetJV(dataJson, "riskCode");//险种代码
                        String policyCarShipTaxDto = GetJV(dataJson, "carShipTax");//车船税保单信息


                        if (!JSONNull.getInstance().equals(dataJson.get("gupolicyitemkindListDto"))) {


                            JSONArray kindList = dataJson.getJSONArray("gupolicyitemkindListDto");
                            for (int b = 0; b < kindList.size(); b++) {

                                JSONObject kindListJson = kindList.getJSONObject(b);
                                String policyNo = GetJV(kindListJson, "policyNo");//保单号码
                                String riskCode = GetJV(kindListJson, "riskCode");//险种代码
                                String kindCode = GetJV(kindListJson, "kindCode");//险别代码
                                String kindName = GetJV(kindListJson, "kindName");//险别名称
                                String startDate = GetJV(kindListJson, "startDate");//起保日期
                                String endDate = GetJV(kindListJson, "endDate");//终保日期
                                String currency = GetJV(kindListJson, "currency");//币别
                                String sumInsured = GetJV(kindListJson, "sumInsured");//保险金额
                                String rate = GetJV(kindListJson, "rate");//费率
                                String shortRate = GetJV(kindListJson, "shortRate");//短期费率
                                String discount = GetJV(kindListJson, "discount");//折扣率
                                String adjustRate = GetJV(kindListJson, "adjustRate");//保费调整比率
                                String priceTaxTotal = GetJV(kindListJson, "priceTaxTotal");//价税合计
                                String grossPremium = GetJV(kindListJson, "grossPremium");//不含税保费
                                String unitInsured = GetJV(kindListJson, "unitInsured");//单位保险金额
                                String quantity = GetJV(kindListJson, "quantity");//数量
                                String pureBenchPremium = GetJV(kindListJson, "pureBenchPremium");//基准纯风险保费
                                String benchmarkPremium = GetJV(kindListJson, "benchmarkPremium");//基准保费
                                String serviceTimes = GetJV(kindListJson, "serviceTimes");//服务次数
                                String deductibleRate = GetJV(kindListJson, "deductibleRate");//绝对免赔率

                                String insertsql1 = '''Insert into PREVIOUSYEARPOLICYINFO_XB
                                                    (
                                                    rec_guid,
                                                    host_orderNo,
                                                    host_policyNo, 
                                                    policyNo,
                                                    riskCode,
                                                    kindCode,
                                                    kindName,
                                                    startDate,
                                                    endDate,
                                                    currency,
                                                    sumInsured,
                                                    rate ,
                                                    shortRate,
                                                    discount,
                                                    adjustRate,
                                                    priceTaxTotal,
                                                    grossPremium ,
                                                    unitInsured,
                                                    quantity,
                                                    pureBenchPremium,
                                                    benchmarkPremium,
                                                    serviceTimes ,
                                                    deductibleRate ,
                                                    Customer_guid,
                                                    createddate,
                                                    objective_guid
                                                    )values(
                                                    sysguid,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,     
                                                    ?,               
                                                    sysdate,
                                                    ?
                                                    )
                                             ''';
                                jt.update(insertsql1,
                                        host_orderNo,
                                        host_policyNo,
                                        policyNo,
                                        riskCode,
                                        kindCode,
                                        kindName,
                                        startDate,
                                        endDate,
                                        currency,
                                        sumInsured,
                                        rate,
                                        shortRate,
                                        discount,
                                        adjustRate,
                                        priceTaxTotal,
                                        grossPremium,
                                        unitInsured,
                                        quantity,
                                        pureBenchPremium,
                                        benchmarkPremium,
                                        serviceTimes,
                                        deductibleRate,
                                        customer_guid, obj_guid);


                            }

                        }


                        if (!JSONNull.getInstance().equals(dataJson.get("orderfcproductListDto"))) {
                            JSONArray FCkindList = dataJson.getJSONArray("orderfcproductListDto");
                            for (int a = 0; a < FCkindList.size(); a++) {
                                JSONObject FCkindListJson = FCkindList.getJSONObject(a);
                                String fcOrderNo = GetJV(FCkindListJson, "fcOrderNo");//非车单号
                                String productCode = GetJV(FCkindListJson, "productCode");//产品代码
                                String productName = GetJV(FCkindListJson, "productName");//产品名称
                                String price = GetJV(FCkindListJson, "price");    //产品保费
                                String sumInsured = GetJV(FCkindListJson, "sumInsured");//保额

                                String insertsql2 = '''
                                                Insert into PREVIOUSYEARPOLICYINFO_FC
                                                    (
                                                    rec_guid,
                                                    host_orderNo,
                                                    host_policyNo, 
                                                    productCode,
                                                    productName,
                                                    price,
                                                    sumInsured,
                                                    customer_guid,
                                                    createddate,objective_guid,fcOrderNo
                                                    )values(
                                                    sysguid,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    sysdate,
                                                    ?,
                                                    ?
                                                    )
                                                   ''';
                                jt.update(insertsql2,
                                        host_orderNo,
                                        host_policyNo,
 productCode, productName, price, sumInsured, customer_guid, obj_guid,fcOrderNo);
                            }

                        }

                        String sumPayTax = null;//车船税汇总金额

                        if (!KHUtil.isNull(policyCarShipTaxDto)) {
                            JSONObject taxjson = JSONObject.fromObject(policyCarShipTaxDto);
                            sumPayTax = GetJV(taxjson, "sumPayTax");


                        }

                        //添加主表信息
                        String insertsql = '''Insert into PREVIOUSYEARPOLICYINFO(
                                                    rec_guid,
                                                    host_orderNo,
                                                    host_policyNo, 
                                                    host_startDate,
                                                    host_endDate,
                                                    host_companyCode,
                                                    host_companyName,
                                                    host_ChannelDetailCode,
                                                    host_riskCode,
                                                    CREATEDDATE,
                                                    CUSTOMER_GUID,
                                                    SUMPAYTAX,Custlistname,objective_guid
                                                    )values(
                                                    sysguid,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?，
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    sysdate,
                                                    ?,
                                                    ?,
                                                    ?,
                                                    ? 
                                                    )
                         ''';
                        jt.update(insertsql, host_orderNo,
                                host_policyNo,
                                host_startDate,
                                host_endDate,
                                host_companyCode,
                                host_companyName,
                                host_ChannelDetailCode,
                                host_riskCode, customer_guid, sumPayTax, CustList_id, obj_guid);

                    }
                }

                    backjson.put("code", 1);
                    backjson.put("msg", "电销系统处理成功！");


                    long endtime = System.currentTimeMillis();

                    log.debug("电销系统接口耗时：" + +(endtime-starttime)+"毫秒");
                } else {
                    backjson.put("code", -1);
                    backjson.put("msg", errmsg);
                }


            }


        } catch (Exception e) {
            log.error("接口处理异常", e);
            backjson.put("code", -1);
            backjson.put("msg", "调用接口处理异常:" + e.getMessage());

        }


        return backjson.toString();
    }

    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
            //log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
                //log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
            } catch (Exception e1) {
                Rev_Value = "";
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }
}
